package org.dromara.netbar.controller;

import java.util.Collections;
import java.util.List;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.constant.NetbarConstants;
import org.dromara.common.core.utils.AssertUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.netbar.domain.bo.*;
import org.dromara.netbar.domain.vo.NetbarCouponMemberVo;
import org.dromara.netbar.domain.vo.NetbarCouponVo;
import org.dromara.netbar.service.INetbarCouponMemberService;
import org.dromara.netbar.service.INetbarMemberLogService;
import org.dromara.netbar.service.impl.MemberService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.netbar.domain.vo.NetbarMemberVo;
import org.dromara.netbar.service.INetbarMemberService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 会员信息管理
 *
 * @author Lion Li
 * @date 2025-06-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/netbar/member")
public class NetbarMemberController extends BaseController {

    private final INetbarMemberService netbarMemberService;
    private final INetbarCouponMemberService netbarCouponMemberService;
    private final INetbarMemberLogService netbarMemberLogService;
    private final MemberService memberService;
    /**
     * 查询会员信息管理列表
     */
    @SaCheckPermission("netbar:member:list")
    @GetMapping("/list")
    public TableDataInfo<NetbarMemberVo> list(NetbarMemberBo bo, PageQuery pageQuery) {
        return netbarMemberService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出会员信息管理列表
     */
    @SaCheckPermission("netbar:member:export")
    @Log(title = "会员信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(NetbarMemberBo bo, HttpServletResponse response) {
        List<NetbarMemberVo> list = netbarMemberService.queryList(bo);
        ExcelUtil.exportExcel(list, "会员信息管理", NetbarMemberVo.class, response);
    }

    /**
     * 获取会员信息管理详细信息
     *
     * @param memberId 主键
     */
    @SaCheckPermission("netbar:member:query")
    @GetMapping("/{memberId}")
    public R<NetbarMemberVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long memberId) {
        return R.ok(netbarMemberService.queryById(memberId));
    }

    /**
     * 新增会员信息管理
     */
    @SaCheckPermission("netbar:member:add")
    @Log(title = "会员信息管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody NetbarMemberBo bo) {
        return toAjax(netbarMemberService.insertByBo(bo));
    }

    /**
     * 修改会员信息管理
     */
    @SaCheckPermission("netbar:member:edit")
    @Log(title = "会员信息管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody NetbarMemberBo bo) {
        return toAjax(netbarMemberService.updateByBo(bo));
    }

    /**
     * 删除会员信息管理
     *
     * @param memberIds 主键串
     */
    @SaCheckPermission("netbar:member:remove")
    @Log(title = "会员信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{memberIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] memberIds) {
        return toAjax(netbarMemberService.deleteWithValidByIds(List.of(memberIds), true));
    }

    /**
     * 查询会员在线信息管理列表
     */
    @SaCheckPermission("netbar:member:list")
    @GetMapping("/onlineList")
    public TableDataInfo<NetbarMemberVo> onlineList(NetbarMemberBo bo, PageQuery pageQuery) {
        return netbarMemberService.queryOnlinePageList(bo, pageQuery);
    }

    // 修改Status
    @SaCheckPermission("netbar:member:openClient")
    @RepeatSubmit()
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@Validated @RequestBody NetbarMemberBo bo) {
        return toAjax(netbarMemberService.changeStatus(bo));
    }

    // 下机
    @SaCheckPermission("netbar:member:shutdown")
    @Log(title = "会员信息管理-下机", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/offline")
    public R<Void> offline(@Validated @RequestBody NetbarMemberBo bo) {
        String tenantId = LoginHelper.getTenantId();
        bo.setTenantId(tenantId);
        return toAjax(netbarMemberService.offline(bo));
    }

    // 添加临时会员
    @SaCheckPermission("netbar:member:add")
    @Log(title = "会员信息管理-添加临时会员", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/addTempMember")
    public R<Void> addTempMember(@Validated @RequestBody NetbarMemberBo bo) {
        String tenantId = LoginHelper.getTenantId();
        bo.setTenantId(tenantId);
        return R.ok(memberService.addTempMember(bo));
    }

    // 上机
    @SaCheckPermission("netbar:member:openClient")
    @Log(title = "会员信息管理-上机", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/openClient")
    public R<?> openClient(@Validated @RequestBody NetbarMemberLoginBo bo) {
        return R.ok(memberService.openClient(bo));
    }

    /**
     * 充值余额
     */
    @SaCheckPermission("netbar:member:balance")
    @Log(title = "会员信息管理-充值余额", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/rechargeBalance")
    public R<Void> rechargeBalance(@Validated @RequestBody NetbarAmountBo bo) {
        memberService.rechargeBalance(bo);
        return R.ok();
    }

    @PostMapping("/readCardSave")
    public R<?> memberReadCardSave(@Validated(AddGroup.class) @RequestBody ReadCardSaveBo bo) {
        String cardno = bo.getCardno();
        AssertUtils.notNull(cardno, "未获取到身份证号!");
        String tenantId = LoginHelper.getTenantId();
        NetbarMemberLogBo netbarMemberLogBo = new NetbarMemberLogBo();
        netbarMemberLogBo.setName(bo.getName());
        netbarMemberLogBo.setIdCardType(bo.getCardTypeName());
        netbarMemberLogBo.setIdCard(cardno);
        netbarMemberLogBo.setDob(bo.getBorn());
        netbarMemberLogBo.setEthnicity(bo.getNation());
        netbarMemberLogBo.setAddress(bo.getAddress());
        netbarMemberLogBo.setPolice(bo.getPolice());
        netbarMemberLogBo.setUserlifeb(bo.getUserlifeb());
        netbarMemberLogBo.setUserlifee(bo.getUserlifee());
        netbarMemberLogBo.setPhotobase64(bo.getPhotobase64());
        netbarMemberLogBo.setFrontImg(bo.getFrontImg());
        netbarMemberLogBo.setBackImg(bo.getBackImg());
        if ("男".equals(bo.getSex())) {
            netbarMemberLogBo.setSex("0");
        }else if("女".equals(bo.getSex())){
            netbarMemberLogBo.setSex("1");
        }else{
            netbarMemberLogBo.setSex(bo.getSex());
        }
        // 写入会员刷卡记录
        netbarMemberLogService.insertByBo(netbarMemberLogBo);
        NetbarMemberVo member = netbarMemberService.getMember(tenantId, bo.getCardno());
        if(null != member){
            // 系统有该会员信息
            return R.ok(member);
        }
        // 没有该会员，新增
        NetbarMemberBo netbarMemberBo = new NetbarMemberBo();
        netbarMemberBo.setMemberName(bo.getName()); // 姓名
        netbarMemberBo.setMemberType("normal"); // 会员类型
        netbarMemberBo.setAccount(bo.getCardno()); // 身份证号
        netbarMemberBo.setSex(netbarMemberLogBo.getSex()); // 性别
        netbarMemberBo.setIdCardType(bo.getCardTypeName()); // 证件类型
        netbarMemberBo.setIdCard(bo.getCardno());
        netbarMemberBo.setDob(bo.getBorn()); //  出生日期
        netbarMemberBo.setEthnicity(bo.getNation()); // 民族
        netbarMemberBo.setAddress(bo.getAddress()); //  地址
        netbarMemberBo.setPolice(bo.getPolice()); // 派出所
        netbarMemberBo.setUserlifeb(bo.getUserlifeb()); // 身份证有效期限-开始
        netbarMemberBo.setUserlifee(bo.getUserlifee()); // 身份证有效期限-结束
        netbarMemberBo.setPhotobase64(bo.getPhotobase64()); // 照片
        netbarMemberBo.setPassword("123456"); // 密码
        netbarMemberBo.setBaseBalance(0L);
        netbarMemberBo.setAwardBalance(0L);
        netbarMemberBo.setStatus(NetbarConstants.Member.DEFAULT_STATUS);
        netbarMemberBo.setTenantId(tenantId);
        Boolean b = netbarMemberService.insertByBo(netbarMemberBo);
        AssertUtils.isTrue(b, "添加失败,请联系管理员！");
        member = netbarMemberService.getMember(tenantId, bo.getCardno());
        return R.ok(member);
//        return netbarMemberLogService.insertByBo(bo)? R.ok() : R.fail("添加失败");
    }

    /**
     * 查询用户充值余额可以使用的代金券
     */
    @SaCheckPermission("netbar:member:balance")
    @GetMapping("/queryDjqListByBalance")
    public R<List<NetbarCouponMemberVo>> queryDjqListByBalance(@RequestParam(value = "memberId") Long memberId,@RequestParam(value = "balance") Long balance) {
        AssertUtils.notNull(memberId, "会员ID不能为空");
        AssertUtils.notNull(balance, "充值余额不能为空");
        List<NetbarCouponMemberVo> couponMemberVoList = netbarCouponMemberService.queryDjqListByBalance(memberId, balance);
        if(couponMemberVoList.isEmpty()){
            return R.ok(couponMemberVoList);
        }
        return R.ok(couponMemberVoList.stream().filter(item -> null != item.getCoupon() &&
            null != item.getCoupon().getEffectiveAmount() &&
            item.getCoupon().getEffectiveAmount() <= balance).toList());
    }

    /**
     * 修改密码
     */
    @Log(title = "会员信息管理-修改密码", businessType = BusinessType.UPDATE)
    @SaCheckPermission("netbar:member:password")
    @PostMapping("/updatePassword")
    public R<?> updatePassword(@RequestBody NetbarMemberUpdatePasswordBo bo) {
        // TODO 密码修改
        AssertUtils.notNull(bo.getMemberId(), "会员不能为空");
//        AssertUtils.notNull(bo.getOldPassword(), "旧密码不能为空");
        AssertUtils.notNull(bo.getNewPassword(), "新密码不能为空");
        // 先获取之前的数据
        NetbarMemberVo member = netbarMemberService.queryById(bo.getMemberId());
        AssertUtils.notNull(member, "会员信息不存在");
//        AssertUtils.isTrue(member.getPassword().equals(bo.getOldPassword()), "旧密码错误");
        netbarMemberService.updateMemberPassword(bo.getMemberId(), bo.getNewPassword());
        return R.ok("修改成功");
    }
}
